<template>
  <el-card style="height: 100%;">
    <div class="card-title">健康数据管理</div>

    <div class="control-btns">
      <el-button type="primary" icon="Plus" @click="openInsertDialog">健康评估</el-button>
    </div>

    <el-table :data="healthDataList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column prop="userName" label="用户名称" align="center"></el-table-column>
      <el-table-column prop="sleepScore" label="睡眠得分" align="center"></el-table-column>
      <el-table-column prop="stressScore" label="压力得分" align="center"></el-table-column>
      <el-table-column prop="exerciseScore" label="锻炼得分" align="center"></el-table-column>
      <el-table-column prop="dietScore" label="饮食得分" align="center"></el-table-column>
      <el-table-column prop="fatigueScore" label="疲劳得分" align="center"></el-table-column>
      <el-table-column prop="totalScore" label="总得分" align="center"></el-table-column>
      <el-table-column prop="createTime" width="200" label="创建时间" align="center"></el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button type="warning" icon="Star" size="small" @click="openResultDialog(scope.row)">评估结果</el-button>

          <el-button type="primary" icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-popconfirm title="是否删除该条数据?" @confirm="deleteRow(scope.row.id)">
            <template #reference>
              <el-button type="danger" icon="DeleteFilled" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>

      </el-table-column>


    </el-table>

    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalData">
    </el-pagination>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑健康数据' : isView ? '查看健康数据' : '新增健康数据'" >
      <el-form :model="healthDataForm" ref="formRef" class="health-form">
        <el-form :model="healthDataForm" ref="formRef"  class="health-form">
          <el-form-item label="您每天的睡眠时间是多少？" prop="sleepScore" class="vertical-form-item">
            <el-radio-group v-model="healthDataForm.sleepScore" :disabled="isView">
              <el-radio :label="0">超过 8 小时（0 分）</el-radio>
              <el-radio :label="1">6-8 小时（1 分）</el-radio>
              <el-radio :label="2">4-6 小时（2 分）</el-radio>
              <el-radio :label="3">少于 4 小时（3 分）</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="您经常感到压力大吗？" prop="stressScore" class="vertical-form-item">
            <el-radio-group v-model="healthDataForm.stressScore" :disabled="isView">
              <el-radio :label="0">很少（0 分）</el-radio>
              <el-radio :label="1">偶尔（1 分）</el-radio>
              <el-radio :label="2">经常（2 分）</el-radio>
              <el-radio :label="3">总是（3 分）</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="您每周的运动次数是多少？" prop="exerciseScore" class="vertical-form-item">
            <el-radio-group v-model="healthDataForm.exerciseScore" :disabled="isView">
              <el-radio :label="0">5 次或更多（0 分）</el-radio>
              <el-radio :label="1">3-4 次（1 分）</el-radio>
              <el-radio :label="2">1-2 次（2 分）</el-radio>
              <el-radio :label="3">很少或没有（3 分）</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="您的饮食习惯如何？" prop="dietScore" class="vertical-form-item">
            <el-radio-group v-model="healthDataForm.dietScore" :disabled="isView">
              <el-radio :label="0">健康均衡（0 分）</el-radio>
              <el-radio :label="1">偶尔吃垃圾食品（1 分）</el-radio>
              <el-radio :label="2">经常吃垃圾食品（2 分）</el-radio>
              <el-radio :label="3">主要吃垃圾食品（3 分）</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="您经常感到疲劳吗？" prop="fatigueScore" class="vertical-form-item">
            <el-radio-group v-model="healthDataForm.fatigueScore" :disabled="isView">
              <el-radio :label="0">很少（0 分）</el-radio>
              <el-radio :label="1">偶尔（1 分）</el-radio>
              <el-radio :label="2">经常（2 分）</el-radio>
              <el-radio :label="3">总是（3 分）</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-form>
      <div v-if="!isView" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHealthData">{{ isEdit ? '编辑' : '新增' }}</el-button>
      </div>
    </el-dialog>

    <!-- 评估结果弹窗 -->
    <el-dialog v-model="resultDialogVisible" title="评估结果">
      <div class="result-stars">
        <el-rate v-model="resultStars" disabled></el-rate>
      </div>
      <div class="result-advice">
        <p>{{ resultAdvice }}</p>
      </div>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { addHealthData, updateHealthData, deleteHealthData, queryDataList, getEvaluationResult } from '@/service/common/health';
import { IHealthData } from "@/views/main/health/data/types";
import showMsg from "@/utils/message/message";

export default defineComponent({
  setup() {
    const healthDataList = ref<IHealthData[]>([]);
    const healthDataForm = ref<IHealthData>({
      createTime: "", id: 0, updateTime: "",
      userName: '',
      userId: 0,
      sleepScore: 0,
      stressScore: 0,
      exerciseScore: 0,
      dietScore: 0,
      fatigueScore: 0,
      totalScore: 0
    });
    const dialogVisible = ref<boolean>(false);
    const resultDialogVisible = ref<boolean>(false);
    const resultStars = ref<number>(0);
    const resultAdvice = ref<string>('');
    const isEdit = ref<boolean>(false);
    const isView = ref<boolean>(false);
    const selectedRows = ref<IHealthData[]>([]);
    const currentPage = ref<number>(1);
    const pageSize = ref<number>(10);
    const totalData = ref<number>(0);

    const fetchHealthData = () => {
      queryDataList(currentPage.value, pageSize.value)
        .then(response => {
          healthDataList.value = response.records;
          totalData.value = response.total;
        })
        .catch(error => {
          console.error("Error fetching health data:", error);
        });
    };

    const openInsertDialog = () => {
      isEdit.value = false;
      isView.value = false;
      dialogVisible.value = true;
      healthDataForm.value = {
        createTime: "", id: 0, updateTime: "",
        userId: 0,
        userName: '',
        sleepScore: 0,
        stressScore: 0,
        exerciseScore: 0,
        dietScore: 0,
        fatigueScore: 0,
        totalScore: 0
      };
    };

    const openEditDialog = (row: IHealthData) => {
      isEdit.value = true;
      isView.value = false;
      dialogVisible.value = true;
      healthDataForm.value = { ...row };
    };

    const openViewDialog = (row: IHealthData) => {
      isEdit.value = false;
      isView.value = true;
      dialogVisible.value = true;
      healthDataForm.value = { ...row };
    };

    const openResultDialog = (row: IHealthData) => {
      resultDialogVisible.value = true;

      getEvaluationResult(row.id)
        .then(response => {
          resultStars.value = response.starts;
          resultAdvice.value = response.advice;
        })
        .catch(error => {
          console.error("Error fetching evaluation result:", error);
        });
    };

    const saveHealthData = () => {
      if (isEdit.value)
      {
        updateHealthData(healthDataForm.value)
          .then(() => {
            dialogVisible.value = false;
            showMsg('success', '健康数据更新成功');
            fetchHealthData();
          })
          .catch(error => {
            console.error("Error updating health data:", error);
          });
      } else {
        addHealthData(healthDataForm.value)
          .then(() => {
            dialogVisible.value = false;
            showMsg('success', '健康数据新增成功');
            fetchHealthData();
          })
          .catch(error => {
            console.error("Error adding health data:", error);
          });
      }
    };

    const handleSelectionChange = (selection: IHealthData[]) => {
      selectedRows.value = selection;
    };

    const deleteRow = (id: number) => {
      deleteHealthData(id)
        .then(() => {
          showMsg('success', '健康数据删除成功');
          fetchHealthData();
        })
        .catch(error => {
          console.error("Error deleting health data:", error);
        });
    };

    const handleSizeChange = (pageSize: number) => {
      pageSize.value = pageSize;
      fetchHealthData();
    };

    const handleCurrentChange = (currentPage: number) => {
      currentPage.value = currentPage;
      fetchHealthData();
    };

    onMounted(() => {
      fetchHealthData();
    });

    return {
      healthDataList,
      healthDataForm,
      dialogVisible,
      resultDialogVisible,
      resultStars,
      resultAdvice,
      isEdit,
      isView,
      currentPage,
      pageSize,
      totalData,
      openInsertDialog,
      openEditDialog,
      openViewDialog,
      openResultDialog,
      saveHealthData,
      handleSelectionChange,
      deleteRow,
      handleSizeChange,
      handleCurrentChange
    };
  }
});
</script>
<style scoped>
.card-title {
  font-size: 20px;
  margin-bottom: 20px;
}

.control-btns {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.vertical-form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.vertical-form-item .el-form-item__label {
 justify-content: flex-start;
width: auto;
margin-bottom: 5px;
}

.vertical-form-item .el-radio-group {
display: flex;
}
</style>
